<?php

namespace app\admin\controller;

use app\admin\common\Base;
use think\Db;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class SeriesDataLogs extends Base
{
	//保修卡列表
	public function index()
	{
		$data = $this->request->param();
		if (isset($data['ajax']) && $data['ajax'] == 1) {
			$page = isset($data['page']) ? $data['page'] : 1;
			$page = intval($page);
			$limit = isset($data['rows']) ? $data['rows'] : 10;
			$limit = intval($limit);
			$start = $limit * ($page - 1);

			if (isset($data['search']) && !empty($data['search'])) {
				if ($data['tj'] == 0) {
					// 资料名称查询
					$list = Db::name('series_data_logs')->where('phone', 'like', '%' . $data['search'] . '%')->select();
					$count = count($list);
				}
			} else {
				$list = Db::name('series_data_logs')->order('id desc')->select();
				$count = count($list);
			}

			foreach ($list as $key => $value) {
				$series_data = Db::name('series_data')->where('id', $value['pid'])->find();
				$list[$key]['series_data_name'] = $series_data['name'];
				$list[$key]['series_name'] = Db::name('series')->where('id', $series_data['pid'])->value('name');
				$list[$key]['addtime'] = date('Y-m-d H:i:s', $value['addtime']);
				$list[$key]['type_name'] = $value['type'] == 0 ? '预览' : '下载';
			}

			return $this->json_data($count, $list);
		}
		return $this->fetch();
	}

	public function add()
	{
		$series = Db::name('series')->select();
		$this->assign('series', $series);
		return $this->fetch();
	}

	//编辑栏目1-1
	public function edit($id)
	{
		if (empty($id)) {
			$info = [];
		} else {
			$info = Db::name('series_data')->where('id', $id)->find();
		}
		$series = Db::name('series')->select();
		$this->assign('series', $series);
		$this->assign('info', $info);
		return $this->fetch();
	}

	// 上传资料
	public function uploads_data()
	{
		$data = $this->request->param();
		if ($data['pid'] == '0') {
			return json(['status' => 0, 'msg' => '请选择系列']);
		}
		if (request()->isPost()) {
			// updata
			if (isset($data['id']) && !empty($data['id'])) {
				$data = array_filter($data, function ($v) {
					return !empty($v);
				});
				$res = Db::name('series_data')->where('id', $data['id'])->update($data);
			}
			// insert
			else {
				$data['addtime'] = time();
				$res = Db::table('series_data')->insert($data);
			}
			if (!$res) {
				return json(['status' => 0, 'msg' => '添加失败']);
			}
			return json(['status' => 1, 'msg' => '添加成功']);
		}
	}

	//删除栏目1-1
	public function del($id)
	{
		$status = 0;
		$msg = "操作失败";
		if (empty($id)) {
			$msg .= '，ID不存在';
		} else {
			$del = Db::name('series_data')->where('id', $id)->delete();
			if ($del) {
				$status = 1;
				$msg = "删除成功";
				adminlog('删除id:' . $id, '删除');
			}
		}
		return ['status' => $status, 'msg' => $msg];
	}
}
